package com.example.a33mvvm.live;

import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.graphics.Color;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.ImageView;

import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.example.a33mvvm.R;
import com.example.a33mvvm.adapter.GiftAdapter;
import com.example.a33mvvm.adapter.MessageAdapter;
import com.example.a33mvvm.databinding.ActivityLiveBinding;
import com.example.a33mvvm.utils.ImageLoader;
import com.example.base_mvvm.entity.MessageEntity;
import com.example.base_mvvm.base.view.BaseView;
import com.example.base_mvvm.base.view.GiftEntity;
import com.example.base_mvvm.entity.FollowEntity;
import com.example.base_mvvm.entity.VideoEntity;
import com.example.base_mvvm.money.Money;
import com.example.base_mvvm.net.Const;

import java.util.ArrayList;
import java.util.List;

import master.flame.danmaku.danmaku.model.BaseDanmaku;
import master.flame.danmaku.danmaku.model.IDanmakus;
import master.flame.danmaku.danmaku.model.android.DanmakuContext;
import master.flame.danmaku.danmaku.model.android.Danmakus;
import master.flame.danmaku.danmaku.parser.BaseDanmakuParser;

public class LiveActivity extends BaseView<ActivityLiveBinding, LiveViewModel> {
    public Money myMoney;
    private MessageAdapter messageAdapter;
    private List<MessageEntity> messages = new ArrayList<>();
    private VideoEntity.DataBean videoBean;
    private GiftAdapter giftAdapter;
    private List<GiftEntity.DataBean> gifts = new ArrayList<>();
    private GiftEntity.DataBean giftBean;

    @Override
    protected void initData() {

        messageAdapter = new MessageAdapter(messages);
        dataBinding.liveChatRoomRv.setLayoutManager(new LinearLayoutManager(this));
        dataBinding.liveChatRoomRv.setAdapter(messageAdapter);
        viewModel.m_success.observe(this, new Observer<Money>() {
            @Override
            public void onChanged(Money money) {
                myMoney = money;

                dataBinding.liveUserMoneyTv.setText("余额" + myMoney.getMoney() + "抖币");

            }
        });
        viewModel.um_failure.observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                ToastUtils.showLong("sjc");
            }
        });


        dataBinding.liveGsyPlayer.getBackButton().setVisibility(View.GONE);
        dataBinding.liveGsyPlayer.setUp(videoBean.getVideopath(), true, "");
        dataBinding.liveGsyPlayer.startPlayLogic();
        viewModel.follow_success.observe(this, new Observer<FollowEntity>() {
            @Override
            public void onChanged(FollowEntity followEntity) {
                if (followEntity.getCode() == 200) {
                    ToastUtils.showLong(followEntity.getMessage());
                    dataBinding.liveBtnFollow.setText("已关注");
                    dataBinding.liveBtnFollow.setBackgroundResource(R.drawable.shape_red);
                    videoBean.setGuanzhu(1);
                } else {
                    ToastUtils.showLong(followEntity.getMessage());
                }
            }
        });
        viewModel.follow_failure.observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                ToastUtils.showLong(s);
            }
        });
        viewModel.noFollow_success.observe(this, new Observer<FollowEntity>() {
            @Override
            public void onChanged(FollowEntity followEntity) {
                if (followEntity.getCode() == 200) {
                    ToastUtils.showLong(followEntity.getMessage());
                    dataBinding.liveBtnFollow.setText("未关注");
                    dataBinding.liveBtnFollow.setBackgroundResource(R.drawable.shape_alpha_black);
                    videoBean.setGuanzhu(0);
                } else {
                    ToastUtils.showLong(followEntity.getMessage());
                }
            }
        });
        viewModel.noFollow_failure.observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                ToastUtils.showLong(s);
            }
        });
        viewModel.gift_success.observe(this, new Observer<GiftEntity>() {
            @Override
            public void onChanged(GiftEntity giftEntity) {
                if (giftEntity.getCode() == 200) {
                    gifts.clear();
                    gifts.addAll(giftEntity.getData());
                    giftAdapter.notifyDataSetChanged();
                } else {
                    ToastUtils.showLong(giftEntity.getMessage());
                }
            }
        });
        viewModel.gift_failure.observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                ToastUtils.showLong(s);
            }
        });
    }

    @Override
    protected void initView() {
        videoBean = (VideoEntity.DataBean) getIntent().getSerializableExtra("dataBean");
        //头像
        ImageLoader.getInstance().LoadImage(this, videoBean.getHeadpath(), dataBinding.liveUserIconIv);
        //用户名
        dataBinding.liveUsernameTv.setText(videoBean.getAuthname());
        //关注状态
        dataBinding.liveBtnFollow.setText(videoBean.getGuanzhu() == 0 ? "未关注" : "已关注");
        //设置关注按钮背景
        dataBinding.liveBtnFollow.setBackgroundResource(videoBean.getGuanzhu() == 0 ? R.drawable.shape_alpha_black : R.drawable.shape_red);
        dataBinding.liveBtnFollow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (videoBean.getGuanzhu() == 0) {
                    //未关注,触发关注接口
                    viewModel.follow(videoBean.getAuthname());
                } else {
                    //已关注,触发取消关注接口
                    viewModel.noFollow(videoBean.getAuthname());
                }
            }
        });
        dataBinding.liveLikeView.addLikeImages(
                R.drawable.ic_favorite_0,
                R.drawable.ic_favorite_1,
                R.drawable.ic_favorite_2,
                R.drawable.ic_favorite_3,
                R.drawable.ic_favorite_4,
                R.drawable.ic_favorite_5,
                R.drawable.ic_favorite_4,
                R.drawable.ic_favorite_3,
                R.drawable.ic_favorite_2,
                R.drawable.ic_favorite_1,
                R.drawable.ic_favorite_0
        );
        //点赞动画
        dataBinding.liveLikeView.setOnClickListener(view -> {
            dataBinding.liveLikeView.addFavor();
        });
        //点击按键弹出输入框
        dataBinding.liveDanmuIv.setOnClickListener(view -> {
            dataBinding.liveDanmuLayoutLl.setVisibility(View.VISIBLE);
        });
        initDanmuView();
        dataBinding.liveDanmuSendIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                sendDanmu();
            }
        });
        dataBinding.liveGiftIv.setOnClickListener(view -> {
            openGiftLayout();
        });
        dataBinding.liveCloseTv.setOnClickListener(view -> {
            closeGiftLayout();
        });
        dataBinding.liveGiftListRv.setLayoutManager(new GridLayoutManager(this, 5));
        giftAdapter = new GiftAdapter(gifts);
        dataBinding.liveGiftListRv.setAdapter(giftAdapter);
        giftAdapter.setOnItemClickListener((adapter, view, position) -> {
            giftBean = gifts.get(position);
            ImageLoader.getInstance().LoadCircleImage(this, giftBean.getGiftpath(), dataBinding.liveGiftSelectIv);
            dataBinding.liveGiftNameTv.setText(giftBean.getGiftname());
        });
        dataBinding.liveGiftSendBtn.setOnClickListener(view -> sendGift());
        getWindow().setStatusBarColor(Color.TRANSPARENT);
    }

    private void sendGift() {


        if (giftBean == null || myMoney == null) {
            ToastUtils.showLong("选礼物");
            return;
        }
        if (myMoney.getMoney() < giftBean.getPrice()) {
            ToastUtils.showLong("没钱刷集贸");
        }
        float newMoney = myMoney.getMoney() - giftBean.getPrice();

        myMoney.setMoney(newMoney);
        viewModel.updateMoney(myMoney);


        //构建一个imageview承载礼物动画
        ImageView giftAnimView = new ImageView(this);
        //直接new的view,需要给他设置基本属性
        ConstraintLayout.LayoutParams params = new ConstraintLayout.LayoutParams(200, 200);
        giftAnimView.setLayoutParams(params);
        dataBinding.liveRootCl.addView(giftAnimView);
        ImageLoader.getInstance().LoadImage(this, giftBean.getGiftpath(), giftAnimView);
        //展示礼物动画
        int screenWidth = dataBinding.liveRootCl.getMeasuredWidth();
        int screenHeight = dataBinding.liveRootCl.getMeasuredHeight();

        //x轴和y轴平移
        ObjectAnimator translationY = ObjectAnimator.ofFloat(giftAnimView, "TranslationY", screenHeight,
                screenHeight / 3, screenHeight / 2);
        ObjectAnimator translationX = ObjectAnimator.ofFloat(giftAnimView, "TranslationX", screenWidth / 2,
                screenWidth / 3 * 2, screenWidth / 2, screenWidth / 3, screenWidth / 2);
        //旋转
        ObjectAnimator rotation = ObjectAnimator.ofFloat(giftAnimView, "Rotation", 0, 1080);
        //缩放
        ObjectAnimator scaleX = ObjectAnimator.ofFloat(giftAnimView, "ScaleX", 1, 2, 1, 3, 1, 2, 1);
        ObjectAnimator scaleY = ObjectAnimator.ofFloat(giftAnimView, "ScaleY", 1, 2, 1, 3, 1, 2, 1);
        //透明度
        ObjectAnimator alpha = ObjectAnimator.ofFloat(giftAnimView, "Alpha", 0.1f, 0.5f, 1.0f, 0.5f, 0.1f);

        AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.setDuration(3000);
        animatorSet.setInterpolator(new AccelerateDecelerateInterpolator());
        animatorSet.playTogether(translationX, translationY, rotation, scaleX, scaleY, alpha);
        animatorSet.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationStart(Animator animation) {
                super.onAnimationStart(animation);
                dataBinding.liveGiftLayoutCl.setVisibility(View.GONE);
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                dataBinding.liveRootCl.removeView(giftAnimView);
            }
        });
        animatorSet.start();
    }

    private void closeGiftLayout() {
        dataBinding.liveGiftLayoutCl.setVisibility(View.GONE);
    }

    private void openGiftLayout() {

        viewModel.getMoney(SPUtils.getInstance().getString(Const.SP_USERNAME));


        dataBinding.liveGiftLayoutCl.setVisibility(View.VISIBLE);
        viewModel.gift();
    }

    private void sendDanmu() {
        String danMu = dataBinding.liveDanmuInputEt.getText().toString();
        if (TextUtils.isEmpty(danMu)) {
            ToastUtils.showLong("请输入弹幕内容!");
            return;
        }
        //清理弹幕
        dataBinding.liveDanmakuView.clear();
        dataBinding.liveDanmakuView.removeAllDanmakus(true);
        //创建弹幕的实体
        BaseDanmaku danmaku = danmakuContext.mDanmakuFactory.createDanmaku(BaseDanmaku.TYPE_SCROLL_LR);
        //设置基础属性
        danmaku.text = danMu;
        danmaku.textSize = 30;
        danmaku.textColor = Color.WHITE;
        danmaku.padding = 10;
        danmaku.setTime(800);
        //添加弹幕到view中
        dataBinding.liveDanmakuView.addDanmaku(danmaku);
        dataBinding.liveDanmakuView.start();
        //清理输入框和隐藏输入框布局
        dataBinding.liveDanmakuView.postDelayed(() -> {
            dataBinding.liveDanmuInputEt.setText("");
            dataBinding.liveDanmuLayoutLl.setVisibility(View.GONE);
        }, 300);
    }

    private DanmakuContext danmakuContext;

    private void initDanmuView() {
        //清理弹幕缓存
        dataBinding.liveDanmakuView.enableDanmakuDrawingCache(false);
        dataBinding.liveDanmakuView.clear();
        dataBinding.liveDanmakuView.removeAllDanmakus(true);
        //创建弹幕上下文
        danmakuContext = DanmakuContext.create();
        //准备弹幕
        dataBinding.liveDanmakuView.prepare(new BaseDanmakuParser() {
            @Override
            protected IDanmakus parse() {
                return new Danmakus();
            }
        }, danmakuContext);
    }

    @Override
    protected Class<LiveViewModel> getViewModel() {
        return LiveViewModel.class;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_live;
    }
}